/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.lai.hospital.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import com.lai.hospital.config.JwtProperties;
import com.lai.hospital.constant.SecurityConst;
import com.lai.hospital.dto.UserDetailDTO;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.lai.hospital.constant.SecurityConst.TOKEN_ALG;
import static com.lai.hospital.constant.SecurityConst.TOKEN_TYPE;

/**
 * jwt工具类
 *
 * @author Mark sunlightcs@gmail.com
 */

@Component
public class JwtUtils {
    private Logger logger = LoggerFactory.getLogger(getClass());

    private String header;

    @Autowired
    JwtProperties jwtProperties;

    public DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(jwtProperties.getSecret())).build().verify(token);
    }


    public static String getUserName(DecodedJWT decodedJWT) {
        return decodedJWT.getClaim("userName").asString();
    }


    /**
     * 生成jwt token
     */
    public String generateJwt(UserDetailDTO loginUser, Boolean rememberMe) {
        Date nowDate = new Date();
        Date expireDate;
        //过期时间
        if(rememberMe){
            expireDate = new Date(nowDate.getTime() + SecurityConst.EXPIRATION_REMEMBER);
        }else {
            expireDate = new Date(nowDate.getTime() + SecurityConst.EXPIRATION);
        }


        JWTCreator.Builder builder = JWT.create();

        builder.withClaim("roles",  loginUser.getAuthorities().toString());
        builder.withClaim("userName", loginUser.getUsername());


        String token = builder
                .withIssuedAt(nowDate)
                .withExpiresAt(expireDate)
                .sign(Algorithm.HMAC256(jwtProperties.getSecret()));
        return token;
    }


    /**
     * token是否过期
     * @return  true：过期
     */
    public boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

}
